//
//  XGHuoShanViewController.swift
//  TodayNews
//
//  Created by monkey on 2020/2/3.
//  Copyright © 2020 itcast. All rights reserved.
//

import UIKit
import SwiftyJSON

class XGHuoShanViewController: UIViewController
{
    private(set) var smallVideos = [XGSmallVideoModel]()
    
    // MARK: - 控制器生命周期方法
    
    override func loadView()
    {
        super.loadView()
        view.addSubview(collectionView)
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        loadData()
    }
    
    // MARK: - 私有属性
    
    private lazy var collectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        let space = TodayNews_Screen_Scale * 2.0
        let width = floor((self.view.width - space) * 0.5)
        let height = floor(width * 1.5)
        flowLayout.itemSize = CGSize(width: width, height: height)
        flowLayout.minimumInteritemSpacing = space
        flowLayout.minimumLineSpacing = space
        let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
        collectionView.backgroundColor = UIColor.white
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.xg_registerCell(cellType: XGSmallVideoCollectionViewCell.self)
        return collectionView
    }()
    private let viewModel = XGHuoShanViewModel()
}

// MARK: - CollectionView数据源和代理

extension XGHuoShanViewController: UICollectionViewDataSource,UICollectionViewDelegate
{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return viewModel.smallVideos.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.xg_dequeueReusableCell(indexPath: indexPath) as XGSmallVideoCollectionViewCell
        cell.smallVideoModel = viewModel.smallVideos[indexPath.item]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {
        let viewController = XGSmallVideoPlayerViewController(currentIndex: indexPath.item, videoList: viewModel.smallVideos)
        navigationController?.pushViewController(viewController, animated: true)
    }
}

// MARK: - 私有扩展

private extension XGHuoShanViewController
{
    func loadData() -> Void
    {
        viewModel.fetchSmallVideoList { (isSuccess) in
            if isSuccess { self.collectionView.reloadData() }
        }
    }
}
